package com.mvetc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class LoginFilter
 * 
 * @author SunZhiQiang
 * @date 2020-06-21
 * 登录过滤器
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
	private String checkedUrls;

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// 获取XML文件中的配置参数
		checkedUrls = fConfig.getInitParameter("checkedUrls");
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// servlet对象转httpServlet对象
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		// 获取url路径
		String servletPath = httpRequest.getServletPath();
		
		// 判断是否为需要检测的网址
		if (servletPath.contains(checkedUrls)) {
			Object sessionUserName = httpRequest.getSession().getAttribute("userName");
			if (sessionUserName == null) {
				httpResponse.sendRedirect("indexbycf.jsp?status=unlogin");
				return;
			}else {
				chain.doFilter(httpRequest, httpResponse);
				return;
			}
		}
		
		// 放行
		chain.doFilter(httpRequest, httpResponse);
	}

}
